package io.renren.modules.oa.controller.api;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.common.utils.dingtalk.DingtalkUtils;
import io.renren.modules.oa.entity.OaPlanConfigEntity;
import io.renren.modules.oa.entity.OaPlanEmployeeEntity;
import io.renren.modules.oa.redis.DingtalkRedis;




@RestController
@RequestMapping("api/attendance")
public class ApiAttendanceController {
	@Autowired
	private RedisUtils redisUtils;
	
	//http://192.168.1.245/renren-admin/api/attendance/index?merchantId=1&months=0
	@RequestMapping(value="/index") 
    public ModelAndView index(@RequestParam(value="merchantId",defaultValue="0")Long merchantId,
			@RequestParam(value="months",defaultValue="0")Integer months,
			HttpServletRequest request, HttpServletResponse response){ 
		//String accessToken = "bf8c15b526d5371fb80b8b9361895b80";
		
		request.setAttribute("list", getList(merchantId, months));
		if(months < 0){
			request.setAttribute("one", "");
			request.setAttribute("two", "weui-bar__item_on");
		}else{
			request.setAttribute("one", "weui-bar__item_on");
			request.setAttribute("two", "");
		}
		
		
		return new ModelAndView("web/index"); 
    }
   
	/**
	 * http://192.168.1.245/renren-admin/api/attendance/index?merchantId=1&months=0
	 * @param merchantId
	 * @param months
	 * @return
	 */
	@GetMapping(value = "index_1")
	public R index_1(@RequestParam(value="merchantId",defaultValue="0")Long merchantId,
			@RequestParam(value="months",defaultValue="0")Integer month,
			HttpServletRequest request, HttpServletResponse response) {
		//String accessToken = DingtalkRedis.getAccessToken(merchantId);
		Map<String, AttendanceModel> result = Maps.newConcurrentMap();
		String accessToken = DingtalkRedis.getAccessToken(merchantId);
		String startTimeString = "";
		String endTimeString = "";
		List<OaPlanEmployeeEntity> employeeList = DingtalkRedis.queryAllList(merchantId);
		// 组装未打卡用户集合
		List<String> userids = Lists.newArrayList();
		for (OaPlanEmployeeEntity oaPlanEmployeeEntity : employeeList) {
			if (oaPlanEmployeeEntity.getActive() == 1) {
				userids.add(oaPlanEmployeeEntity.getUserid());
				result.put(oaPlanEmployeeEntity.getUserid(), new AttendanceModel(oaPlanEmployeeEntity.getUserid(),oaPlanEmployeeEntity.getName(), oaPlanEmployeeEntity.getAvatar(), 0, 0));
			}
		}
		
		Date startTime = DateUtils.getStartTime(new Date(), month);  //获取月份第一天
		int monthDays = DateUtils.getDayOfMonth(startTime);	//每月天数
		int weeks = monthDays / 7;
		int days = monthDays % 7;
		
		System.out.println("本月"+monthDays + "天," + weeks + "周,剩余" + days+"天");
		Long oneDay = 1000 * 60 * 60 * 24l;
		long start = startTime.getTime();
		for (int i = 1; i <= weeks; i++) {
			startTimeString = DateUtils.getStartTimeString(new Date(start));
			endTimeString = DateUtils.getEndTimeString(new Date(start+(oneDay*6)));
			result = attendanceList(1L,50L,accessToken, startTimeString, endTimeString, userids, result);
			//System.out.print("====");
			//System.out.println();
			//System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*6))), Arrays.asList(uids)));
			start = new Date(start+(oneDay*7)).getTime();
		}
		if(days > 0){
			startTimeString = DateUtils.getStartTimeString(new Date(start));
			endTimeString = DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1))));
			result = attendanceList(1L, 50L,accessToken, startTimeString, endTimeString, userids, result);
			//System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1)))), Arrays.asList(uids)));
		}
		List<AttendanceModel> list = Lists.newArrayList();
		for (OaPlanEmployeeEntity employee : employeeList) {
			if (employee.getActive() == 1) {
				list.add(result.get(employee.getUserid()));
			}
		}
		return R.ok().put("result", result);
	}
	
	// 获取部门下的所有员工userId
	private static Map<String, AttendanceModel> attendanceList(Long pageNo,Long pageSize,String accessToken,String startTime,String endTime, List<String> userids,Map<String, AttendanceModel> result) {
		System.out.println("startTime:"+startTime+",endTime:"+endTime);
		if (userids != null && userids.size() > 0) {
			String r = DingtalkUtils.attendanceList(accessToken ,startTime,endTime, userids, pageNo, pageSize);
			System.out.println(r);
			JSONObject json = new JSONObject(r);
			if (json.has("errcode") && json.getLong("errcode") == 0L) {
				
				JSONArray record = json.getJSONArray("recordresult");
				for (int i = 0; i< record.length(); i++) {
					JSONObject jo = record.getJSONObject(i);
					
					String userid = jo.getString("userId");
					Long userCheckTime = jo.getLong("userCheckTime");
					Date checkTime = DateUtils.timeStamp2Date(userCheckTime+"", DateUtils.DATE_TIME_PATTERN);
					//System.out.println(result.get(userid).getName() +"=="+checkTime);
					//System.out.println(DateUtils.isFanbu(checkTime));
					//System.out.println(DateUtils.isJiaban(checkTime));
					AttendanceModel model = result.get(userid);
					if(DateUtils.isFanbu(checkTime)){
						model.setFanbu(model.getFanbu() + 1);
					}
					if(DateUtils.isJiaban(checkTime)){
						model.setJiaban(model.getJiaban() + 1);
					}
				}
				if (json.getBoolean("hasMore")) {
					return attendanceList(pageNo+1, pageSize, accessToken, startTime, endTime, userids, result);
				}
			} 
		}
		return result;
	}

	public List<AttendanceModel> getList(Long merchantId,Integer months) {
		String key = "attendance_model_"+merchantId+"_"+months+"_"+DateUtils.format(new Date());
		Object attendanceModelList = redisUtils.get(key);
		if (attendanceModelList != null) {
			return (List<AttendanceModel>)attendanceModelList;
		}else{
			Map<String, AttendanceModel> result = Maps.newConcurrentMap();
			String accessToken = DingtalkRedis.getAccessToken(merchantId);
			String startTimeString = "";
			String endTimeString = "";
			List<OaPlanEmployeeEntity> employeeList = DingtalkRedis.queryAllList(merchantId);
			// 组装未打卡用户集合
			List<String> userids = Lists.newArrayList();
			for (OaPlanEmployeeEntity oaPlanEmployeeEntity : employeeList) {
				if (oaPlanEmployeeEntity.getActive() == 1) {
					userids.add(oaPlanEmployeeEntity.getUserid());
					result.put(oaPlanEmployeeEntity.getUserid(), new AttendanceModel(oaPlanEmployeeEntity.getUserid(),oaPlanEmployeeEntity.getName(), oaPlanEmployeeEntity.getAvatar(), 0, 0));
				}
			}
			
			Date startTime = DateUtils.getStartTime(new Date(), months);  //获取月份第一天
			int monthDays = DateUtils.getDayOfMonth(startTime);	//每月天数
			int weeks = monthDays / 7;
			int days = monthDays % 7;
			
			System.out.println("本月"+monthDays + "天," + weeks + "周,剩余" + days+"天");
			Long oneDay = 1000 * 60 * 60 * 24l;
			long start = startTime.getTime();
			for (int i = 1; i <= weeks; i++) {
				startTimeString = DateUtils.getStartTimeString(new Date(start));
				endTimeString = DateUtils.getEndTimeString(new Date(start+(oneDay*6)));
				result = attendanceList(1L,50L,accessToken, startTimeString, endTimeString, userids, result);
				//System.out.print("====");
				//System.out.println();
				//System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*6))), Arrays.asList(uids)));
				start = new Date(start+(oneDay*7)).getTime();
			}
			if(days > 0){
				startTimeString = DateUtils.getStartTimeString(new Date(start));
				endTimeString = DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1))));
				result = attendanceList(1L, 50L,accessToken, startTimeString, endTimeString, userids, result);
				//System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1)))), Arrays.asList(uids)));
			}
			List<AttendanceModel> list = Lists.newArrayList();
			for (OaPlanEmployeeEntity employee : employeeList) {
				if (employee.getActive() == 1) {
					list.add(result.get(employee.getUserid()));
				}
			}
			if(list != null && list.size() > 0){
				redisUtils.set(key, list, 3600 * 4);
			}
			return list;
		}
	}
    

}
